var pay = {
    servers: {
        /*
        $sid: {
            $day: 0
        }
        */
    },
    updateTime: 0,

    load: function(callback) {
        if (fs.existsSync('data/pays.json')) {
            this.servers = JSON.parse(fs.readFileSync('data/pays.json'));
            for (var sid in this.servers) {
                this.updateTime = Math.max.apply(null, Object.keys(this.servers[sid]));
                break;
            }
            callback();
            return;
        }
        
        var servers = {};

        async.each(gServers.getSids(), function(sid, cb) {
            var db = gServers.getGameDB(sid);
            if (!db) {
                cb(); return;
            }
		    var keyf = function(doc){
                return {'time': doc.time.substring(0, 10)};
            }
		    var reduce = function(doc, prev) {
                prev.sum += +obj.amt;
            }
            db.collection('pay').group(keyf, {}, {'sum':0}, reduce, function(err, results) {
                if (err || !results) {
                    cb(util.format('server %d db error', sid)); return;
                }

                var days = {};
                results.forEach(function(value){
                    var time = new Date(value.time + ' 00:00:00');
                    days[time.getStamp()] = parseInt(value.sum * config.platform.exchange_rate);
                });
                servers[sid] = days;
                LOG(util.format('load server %s pay success', sid));
                cb();
            });
        }, function(err) {
            this.servers = servers;
            this.updateTime = (new Date()).zeroTime().getStamp();
            callback(err);
        }.bind(this));
    },

    save: function(callback) {
        LOG('pay save');
        fs.writeFileSync('data/pays.json', JSON.stringify(this.servers));
    },

    update: function(zeroTime, callback) {
        var minTime = Math.min(zeroTime, this.updateTime);
        var minTime = Date.createFromStamp(minTime).stdFormatedString();
        var maxTime = Date.createFromStamp(zeroTime + 86400).stdFormatedString();
        
        var counts = {};
        async.each(gServers.getSids(), function(sid, cb) {
            var db = gServers.getGameDB(sid);
            if (!db) {
                cb(); return;
            }
            
            var days = this.servers[sid];
            if (!days) {
                days = {};
                this.servers[sid] = days;
            }

		    var keyf = function(doc){
                return {'time': doc.time.substring(0, 10)};
            }
		    var reduce = function(doc, prev) {
                prev.sum += +obj.amt;
            }
            var condition = {'time':{'$gte':minTime, '$lt':maxTime}};
            db.collection('pay').group(keyf, condition, {'sum':0}, reduce, function(err, results) {
                if (err || !results) {
                    cb(util.format('server %d db error %j', sid, err)); return;
                }

                results.forEach(function(value){
                    var time = new Date(value.time + ' 00:00:00');
                    days[time.getStamp()] = parseInt(value.sum * config.platform.exchange_rate);
                });

                cb();
            });
        }.bind(this), function(err) {
            if (!err) {
                this.updateTime = zeroTime;

            }
            callback(err);
        }.bind(this));
    },
}

exports.pay = pay;
